﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Security.Cryptography;
using System.IO;
using System.Text;

using CE.Image;
using CE.User;
using CE.Mail;
using CE.Global;
using CE.Security;

public partial class car_insurance_call_me : MyLanguageBasePage
{
    protected override void InitializeCulture()
    {
        String selectedCulture = CE.Global.General.SetCulture();
        base.InitializeCulture();
    }

    string _redirectUrl = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        Master.Page.Title = Resources.Title.CallMeBackTitle;
        if (!IsPostBack)
        {
            //GetCookies();
            Session["UMMSG"] = null;
            //txtCarModel.Attributes.Add("onblur", "ShowValidationEffect('" + txtCarModel.ClientID + "','" + rfvCarModel.ClientID + "');");
            //txtCarPlate.Attributes.Add("onblur", "ShowValidationEffect('" + txtCarPlate.ClientID + "','" + rfvCarPlate.ClientID + "');");
            txtEmail.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtEmail.ClientID + "','" + rfvEmail.ClientID + "','" + revEmail.ClientID + "');");
            txtName.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtName.ClientID + "','" + rfvName.ClientID + "','" + revName.ClientID + "');");
            txtMobile.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtMobile.ClientID + "','" + rfvMobile.ClientID + "','" + revMobile.ClientID + "');");
            ddlCallMeTime.Attributes.Add("onblur", "ShowValidationEffect('" + ddlCallMeTime.ClientID + "','" + rfvCallMeTime.ClientID + "');");
            Page.Form.DefaultButton = btnSubmit.UniqueID;
            if (Session[CE.Global.General.UserEmail] != null && Session[CE.Global.General.UserName] != null && Session[CE.Global.General.UserPhoneNo] != null)
            {
                txtName.Text = Session[CE.Global.General.UserName].ToString();
                txtEmail.Text = Session[CE.Global.General.UserEmail].ToString();
                txtMobile.Text = Session[CE.Global.General.UserPhoneNo].ToString();
            }
            if (Session[CE.Global.General.IsAcceptTC] != null)
            {
                checkIsAgreement.Checked = true;
                if (Session[CE.Global.General.IsAcceptTC].ToString() != "1")
                {
                    checkIsAgreement.Checked = false;
                }
            }

            vsCustomer.HeaderText = GetGlobalResourceObject("General", "RequiredValidation").ToString() + "<br \">" + GetGlobalResourceObject("General", "TickCheckbox").ToString();
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        ChangeValidationEffectServerSide("callme");
        Page.Validate("callme");
        if (Page.IsValid)
        {
            if (txtMobile.Text.Trim().Length == 10)
            {
                int _isexistuser = 1;
                Int64 _userId = 0;
                Account _useraccount = new Account();
                AccountDB _useraccountdb = new AccountDB();

                _useraccount = _useraccountdb.GetUserAccount(EmailAddress, Convert.ToInt32(CE.Global.CEUserType.Customer));
                //Hide on 13 Nov 2014 //_useraccount = _useraccountdb.GetUserAccount(EmailAddress, MobileNumber, Convert.ToInt32(CE.Global.CEUserType.Customer));
                if (_useraccount != null && _useraccount.CEID > 0)
                {
                    _userId = _useraccount.CEID;
                    Profile _userprofile = new Profile();
                    ProfileDB _userprofiledb = new ProfileDB();

                    Contact _usercontact = new Contact();
                    ContactDB _usercontactdb = new ContactDB();

                    Session[CE.Global.General.StartTime] = General.GetUTCDateTime().ToString();
                    _userprofile = _userprofiledb.GetProfile(_useraccount.CEID);

                    if (_userprofile != null && _userprofile.ProfileId > 0)
                    {
                        _userprofile.SurName = string.Empty;
                        _userprofile.FirstName = Server.HtmlEncode(txtName.Text);
                        _userprofile.IsAcceptTC = checkIsAgreement.Checked;
                        _userprofiledb.Insert(_userprofile);
                    }
                    _usercontact = _usercontactdb.GetContact(_useraccount.CEID);
                    if (_usercontact != null && _usercontact.ContactId > 0)
                    {
                        _usercontact.Mobile = txtMobile.Text.Trim();
                        _usercontactdb.Insert(_usercontact);
                    }
                    Session[CE.Global.General.UserId] = _useraccount.CEID;
                    Session[CE.Global.General.UserTypeId] = _useraccount.UserTypeId;
                    Session[CE.Global.General.UserEmail] = _useraccount.Email;
                    Session[CE.Global.General.UserName] = _userprofile.FirstName;
                    Session[CE.Global.General.IsAcceptTC] = "0";
                    if (_userprofile.IsAcceptTC == true)
                    {
                        Session[CE.Global.General.IsAcceptTC] = "1";
                    }
                    Session[CE.Global.General.UserPhoneNo] = _usercontact.Mobile;
                    _useraccount = null;
                    _useraccountdb = null;
                    _userprofile = null;
                    _userprofiledb = null;
                    _usercontact = null;
                    _usercontactdb = null;
                }
                else
                {
                    _isexistuser = 0;
                    if (UpdateProfile(_userId, 0) > 0)
                    {
                        SendMailToUser(EmailAddress, Name, MobileNumber); //txtEmailAddress.Text.Trim()

                        Session["CLASSTYPE"] = "1";
                        ScriptManager.RegisterStartupScript(Page, this.GetType(), "alertThxU", "alert('Saved successfully!');", true);
                        _userId = Convert.ToInt64(Session[General.UserId].ToString());
                        _isexistuser = 0;
                    }
                }
                SetCookies(Session[CE.Global.General.UserName].ToString(), Session[CE.Global.General.UserEmail].ToString(), Session[CE.Global.General.UserPhoneNo].ToString());

                string _message = "";
                string _title = "";

                txtName.Text = General.ClearScriptTag(txtName.Text);
                _message = "Customer Name: " + Server.HtmlEncode(txtName.Text);
                _title = "Car not found - Call me now - Request by " + Server.HtmlEncode(txtName.Text);
                if (IsValid)
                {
                    Int64 _result = 0;
                    ContactUser _cu = new ContactUser();
                    ContactUserDB _cudb = new ContactUserDB();

                    string strInsType = "1";

                    _cu.InsuranceType = "CI-" + strInsType;


                    //_cu.ProductId = Convert.ToInt64(Session[General.CarId].ToString());
                    _cu.RefCEUserId = _userId;

                    _cu.ProviderCompanyId = 0;
                    _cu.ContactNo = txtMobile.Text.Trim();
                    _cu.FullName = Server.HtmlEncode(txtName.Text);
                    _cu.CallTime = Convert.ToInt16(ddlCallMeTime.Text);

                    if (Request.Params["spc"] != null)
                    {
                        if (Request.Params["spc"].ToString() == "1")
                        {
                            _cu.Info1 = "GG Promotion";
                        }
                    }
                    _cu.Info2 = "CARNOTFOUND";// Server.HtmlEncode(txtCarModel.Text);
                    _cu.Info3 = "WEB";// Server.HtmlEncode(txtCarPlate.Text);

                    _result = _cudb.Insert(_cu);

                    if (_result > 0)
                    {
                        ScriptManager.RegisterStartupScript(Page, this.GetType(), "alertThxU", "alert('" + Resources.CarInsurance.CallMeMessage + "')", true);

                        #region Hide Call me email sending - Sakthi on 11 Dec 2014
                        ////_message += "<br/><br/>Car Model : " + txtCarModel.Text.Trim();
                        ////_message += "<br/><br/>Car Plate Number : " + txtCarPlate.Text.Trim();
                        //_message += "<br/><br/>Email : " + txtEmail.Text;
                        //_message += "<br/><br/>Contact No : " + txtMobile.Text.Trim();
                        //_message += "<br/><br/>Call Time : " + ddlCallMeTime.SelectedItem.Text;
                        //string _emailList = ConfigurationManager.AppSettings["TH.CICallMeMessageReceiver"].ToString();
                        //MyMailManager.SendCRMMessage(_emailList, _title, _message);
                        #endregion

                        if (_isexistuser == 1)
                        {
                            //Hide on 11 Dec 2014//GetUser(_userId);
                        }
                        _redirectUrl = CE.Global.General.GetUrl("/user/user-message", Page);
                        Session["UMMSG"] = "UMG,1994";
                        Response.Redirect(_redirectUrl);

                    }
                    else
                    {
                        ScriptManager.RegisterStartupScript(Page, this.GetType(), "alertThxU", "alert('Saving did NOT succees!');", true);
                    }
                }
            }
        }
    }

    private Int64 UpdateProfile(Int64 UserId, Int64 CarId)
    {
        Int64 _retValue = 0;

        if (UserId != 0)
        {
            Profile _profile = new Profile();
            ProfileDB _profiledb = new ProfileDB();

            Contact _contact = new Contact();
            ContactDB _contactdb = new ContactDB();

            _profile = _profiledb.GetProfile(UserId);
            _contact = _contactdb.GetContact(UserId);
            _retValue = UserId;
            if (_profile != null)
            {
                #region Update Profile

                _profile.Salutation = "";
                txtName.Text = CE.Global.General.ClearScriptTag(txtName.Text.Trim());
                _profile.FirstName = HttpUtility.HtmlEncode(txtName.Text);
                _profile.SurName = "";
                if (_profile.DOB.Year == 1900)
                {
                    DateTime dteDOB = new DateTime(1995, 1, 1);
                    _profile.DOB = dteDOB;
                }
                if (_profile.Gender.ToString().Trim() == "")
                {
                    _profile.Gender = 'M';
                }
                _profile.Status = "Complete";
                _profile.IsAcceptTC = checkIsAgreement.Checked;

                _retValue = _profiledb.Insert(_profile);

                if (_retValue > 0 && _contact != null)
                {
                    _contact.Mobile = txtMobile.Text.Trim();
                    _contact.Status = true;

                    _retValue = _contactdb.Insert(_contact);
                }

                if (_retValue > 0)
                {
                    if (_profile.FirstName != string.Empty)
                    {
                        Session[CE.Global.General.UserName] = _profile.FirstName + " " + _profile.SurName;
                    }
                    else
                    {
                        Session[CE.Global.General.UserName] = _profile.SurName;
                    }
                    Session[CE.Global.General.IsAcceptTC] = "0";
                    if (_profile.IsAcceptTC == true)
                    {
                        Session[CE.Global.General.IsAcceptTC] = "1";
                    }
                    if (_contact != null)
                    {
                        Session[General.UserPhoneNo] = _contact.Mobile;
                    }
                    Session[CE.Global.General.UserProfileAndContactComplete] = "1";
                    if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) == Convert.ToInt32(CE.Global.CEUserType.Provider))
                    {
                        Session[CE.Global.General.ProviderProfileFirstTime] = "0";
                    }
                }

                _profile = null;
                _contact = null;
                #endregion
            }
        }
        else
        {
            _retValue = SaveNewCustomer();
            UserId = _retValue;
        }
        return _retValue;
    }

    private Int64 SaveNewCustomer()
    {
        #region New Customer
        Int64 _retVal = 0;
        if (Page.IsValid)
        {

            Account _useraccount = new Account();
            AccountDB _useraccountdb = new AccountDB();

            Profile _userprofile = new Profile();
            ProfileDB _userprofiledb = new ProfileDB();

            Contact _contact = new Contact();
            ContactDB _contactdb = new ContactDB();

            _useraccount = _useraccountdb.GetUserAccount(txtEmail.Text.Trim(), Convert.ToInt32(CE.Global.CEUserType.Customer));
            //Hide on 13 Nov 2014 //_useraccount = _useraccountdb.GetUserAccount(txtEmail.Text.Trim(), txtMobile.Text.Trim().ToLower(), Convert.ToInt32(CE.Global.CEUserType.Customer));
            if (_useraccount != null)
            {
                if (_useraccount.CEID > 0)
                {
                    _retVal = _useraccount.CEID;
                    _contact = _contactdb.GetContact(_useraccount.CEID);
                    Session[CE.Global.General.UserId] = _useraccount.CEID;
                    Session[CE.Global.General.UserTypeId] = _useraccount.UserTypeId;
                    Session[CE.Global.General.UserEmail] = _useraccount.Email;
                    Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
                    Session[CE.Global.General.StartTime] = General.GetUTCDateTime().ToString();
                    _userprofile = _userprofiledb.GetProfile(_useraccount.CEID);
                    if (_userprofile != null && _userprofile.ProfileId > 0)
                    {
                        if (_userprofile.FirstName != string.Empty)
                        {
                            Session[CE.Global.General.UserName] = _userprofile.FirstName + " " + _userprofile.SurName;
                        }
                        else
                        {
                            Session[CE.Global.General.UserName] = _userprofile.SurName;
                        }
                    }
                }
            }
            else
            {

                long _result = -1;
                _useraccount = new Account();
                _useraccount.Email = txtEmail.Text.Trim().ToLower();
                string _authcode = txtMobile.Text.Trim();
                _useraccount.AuthCode = _authcode;
                _useraccount.UserId = "CEUSERAUTOIDCI";
                _useraccount.UserTypeId = Convert.ToInt32(CE.Global.CEUserType.Customer);
                _useraccount.IsAcceptTC = false;
                _useraccount.Status = true;
                _useraccount.RefCEUserID = -1;
                _result = _useraccountdb.Insert(_useraccount);
                _useraccount.CEID = _result;
                _retVal = _useraccount.CEID;
                if (_result > 0)
                {
                    _userprofile.Salutation = "";
                    _userprofile.FirstName = Server.HtmlEncode(txtName.Text);
                    _userprofile.SurName = "";
                    DateTime dteDOB = new DateTime(1995, 1, 1);
                    _userprofile.DOB = dteDOB;
                    _userprofile.Gender = 'M';

                    _userprofile.Occupation = Convert.ToInt32("54");
                    _userprofile.Status = "Complete";
                    _userprofile.RefCEUserId = _useraccount.CEID;
                    _userprofile.IsAcceptTC = checkIsAgreement.Checked;
                    _result = _userprofiledb.Insert(_userprofile);

                    _contact.Email = _useraccount.Email;
                    _contact.Mobile = txtMobile.Text.Trim();

                    _contact.Status = true;
                    _contact.RefCEUserId = _useraccount.CEID;
                    _result = _contactdb.Insert(_contact);

                    if (_result > 0)
                    {
                        Session[CE.Global.General.UserId] = _useraccount.CEID;
                        Session[CE.Global.General.UserTypeId] = _useraccount.UserTypeId;
                        Session[CE.Global.General.UserEmail] = _useraccount.Email;
                        Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
                        Session[CE.Global.General.StartTime] = General.GetUTCDateTime().ToString();
                        if (_userprofile.FirstName != string.Empty)
                        {
                            Session[CE.Global.General.UserName] = _userprofile.FirstName + " " + _userprofile.SurName;
                        }
                        else
                        {
                            Session[CE.Global.General.UserName] = _userprofile.SurName;
                        }
                        Session[CE.Global.General.UserProfileAndContactComplete] = "1";
                        Session[CE.Global.General.IsAcceptTC] = "0";
                        if (_userprofile.IsAcceptTC == true)
                        {
                            Session[CE.Global.General.IsAcceptTC] = "1";
                        }
                    }

                }

            }
        }
        else
        {
            _retVal = 0;
        }

        return _retVal;
        #endregion
    }

    private bool SendMailToUser(string EmailAddress, string UserName, string AuthCode)
    {
        bool _retVal = false;
        _retVal = CE.Email.Welcome.SendMail(EmailAddress, UserName, AuthCode);
        return _retVal;
    }

    private string EmailAddress
    {
        get { return txtEmail.Text.Trim(); }
    }

    private string MobileNumber
    {
        get { return txtMobile.Text.Trim(); }
    }

    private string Name
    {
        get { return txtName.Text.Trim(); }
    }

    private void ChangeValidationEffectServerSide(string strValidationGroup)
    {
        //txtCarModel.Text = HttpUtility.HtmlEncode(txtCarModel.Text);
        //txtCarPlate.Text = HttpUtility.HtmlEncode(txtCarPlate.Text);
        txtName.Text = HttpUtility.HtmlEncode(txtName.Text);
        txtEmail.Text = HttpUtility.HtmlEncode(txtEmail.Text);
        txtMobile.Text = HttpUtility.HtmlEncode(txtMobile.Text);

        #region Customer

        //Car Model
        //if (rfvCarModel.Enabled && rfvCarModel.ValidationGroup == strValidationGroup)
        //{
        //    rfvCarModel.Validate();
        //    if (rfvCarModel.IsValid == false)
        //    {
        //        txtCarModel.ControlStyle.CssClass = "input-fields validationError";
        //    }
        //    else
        //    {
        //        txtCarModel.ControlStyle.CssClass = "input-fields";
        //    }
        //}
        //else
        //{
        //    txtCarModel.ControlStyle.CssClass = "input-fields";
        //}
        //Car Plate
        //if (rfvCarPlate.Enabled && rfvCarPlate.ValidationGroup == strValidationGroup)
        //{
        //    rfvCarPlate.Validate();
        //    if (rfvCarPlate.IsValid == false)
        //    {
        //        txtCarPlate.ControlStyle.CssClass = "input-fields validationError";
        //    }
        //    else
        //    {
        //        txtCarPlate.ControlStyle.CssClass = "input-fields";
        //    }
        //}
        //else
        //{
        //    txtCarPlate.ControlStyle.CssClass = "input-fields";
        //}
        //Email
        if (rfvName.Enabled && rfvName.ValidationGroup == strValidationGroup)
        {
            rfvName.Validate();
            if (rfvName.IsValid == false)
            {
                txtName.ControlStyle.CssClass = "input-fields validationError";
            }
            else
            {
                txtName.ControlStyle.CssClass = "input-fields";
            }
        }
        else
        {
            txtName.ControlStyle.CssClass = "input-fields";
        }

        if (revName.Enabled && revName.ValidationGroup == strValidationGroup)
        {
            if (rfvName.IsValid)
            {
                revName.Validate();
                if (revName.IsValid == false)
                {
                    txtName.ControlStyle.CssClass = "input-fields validationError";
                }
                else
                {
                    txtName.ControlStyle.CssClass = "input-fields";
                }
            }
        }
        else
        {
            txtName.ControlStyle.CssClass = "input-fields";
        }

        //Email
        if (rfvEmail.Enabled && rfvEmail.ValidationGroup == strValidationGroup)
        {
            rfvEmail.Validate();
            if (rfvEmail.IsValid == false)
            {
                txtEmail.ControlStyle.CssClass = "input-fields validationError";
            }
            else
            {
                txtEmail.ControlStyle.CssClass = "input-fields";
            }
        }
        else
        {
            txtEmail.ControlStyle.CssClass = "input-fields";
        }

        if (revEmail.Enabled && revEmail.ValidationGroup == strValidationGroup)
        {
            if (rfvEmail.IsValid)
            {
                revEmail.Validate();
                if (revEmail.IsValid == false)
                {
                    txtEmail.ControlStyle.CssClass = "input-fields validationError";
                }
                else
                {
                    txtEmail.ControlStyle.CssClass = "input-fields";
                }
            }
        }
        else
        {
            txtEmail.ControlStyle.CssClass = "input-fields";
        }

        //MobileNo
        if (rfvMobile.Enabled && rfvMobile.ValidationGroup == strValidationGroup)
        {
            rfvMobile.Validate();
            if (rfvMobile.IsValid == false)
            {
                txtMobile.ControlStyle.CssClass = "input-fields validationError";
            }
            else
            {
                txtMobile.ControlStyle.CssClass = "input-fields";
            }
        }
        else
        {
            txtMobile.ControlStyle.CssClass = "input-fields";
        }

        if (revMobile.Enabled && revMobile.ValidationGroup == strValidationGroup)
        {
            if (rfvMobile.IsValid)
            {
                revMobile.Validate();
                if (revMobile.IsValid == false)
                {
                    txtMobile.ControlStyle.CssClass = "input-fields validationError";
                }
                else
                {
                    txtMobile.ControlStyle.CssClass = "input-fields";
                }
            }
        }
        else
        {
            txtMobile.ControlStyle.CssClass = "input-fields";
        }

        //CallMeTime
        if (rfvCallMeTime.Enabled && rfvCallMeTime.ValidationGroup == strValidationGroup)
        {
            rfvCallMeTime.Validate();
            if (rfvCallMeTime.IsValid == false)
            {
                ddlCallMeTime.ControlStyle.CssClass = "input-fields-dropdown validationError";
            }
            else
            {
                ddlCallMeTime.ControlStyle.CssClass = "input-fields-dropdown";
            }
        }
        else
        {
            ddlCallMeTime.ControlStyle.CssClass = "input-fields-dropdown";
        }

        #endregion
    }

    private void SetCookies(string Name, string Email, string Mobile)
    {
        try
        {
            HttpCookie _cookie = new HttpCookie("GGQuote");
            _cookie.Values.Add("CustomerName", MySecurity.Encrypt(Name, true));
            _cookie.Values.Add("CustomerEmail", MySecurity.Encrypt(Email, true));
            _cookie.Values.Add("CustomerMobile", MySecurity.Encrypt(Mobile, true));

            _cookie.Expires = DateTime.Now.AddDays(60);
            Response.Cookies.Add(_cookie);
        }
        catch (Exception Ex)
        {
            Ex = null;
        }
    }

    private void GetUser(Int64 UserId)
    {
        try
        {
            Profile _profile = new Profile();
            ProfileDB _profiledb = new ProfileDB();

            Contact _contact = new Contact();
            ContactDB _contactdb = new ContactDB();

            _profile = _profiledb.GetProfile(UserId);
            _contact = _contactdb.GetContact(UserId);

            if (_profile != null)
            {

                if (_profile.FirstName != string.Empty)
                {
                    Session[CE.Global.General.UserName] = _profile.FirstName + " " + _profile.SurName;
                }
                else
                {
                    Session[CE.Global.General.UserName] = _profile.SurName;
                }
                if (_contact != null && _contact.Mobile != string.Empty)
                {
                    Session[General.UserPhoneNo] = _contact.Mobile;
                }
                Session[CE.Global.General.UserProfileAndContactComplete] = "1";
                if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
                    Convert.ToInt32(CE.Global.CEUserType.Provider))
                {
                    Session[CE.Global.General.ProviderProfileFirstTime] = "0";
                }
                SetCookies(Session[CE.Global.General.UserName].ToString(), _contact.Email, _contact.Mobile);

                _profile = null;
                _contact = null;
            }
        }
        catch (Exception ex)
        {
        }
    }

    private void GetCookies()
    {
        try
        {
            HttpCookie _cookie = Request.Cookies.Get("GGQuote");
            if (_cookie != null)
            {
                txtName.Text = MySecurity.Decrypt(_cookie.Values.Get("CustomerName"), true);
                txtEmail.Text = MySecurity.Decrypt(_cookie.Values.Get("CustomerEmail"), true);
                string _mobile = MySecurity.Decrypt(_cookie.Values.Get("CustomerMobile"), true);
                txtMobile.Text = _mobile;
                //txtEmail.ReadOnly = true;
            }
        }
        catch (Exception Ex)
        {
            Ex = null;
        }
    }

}
